import { NextRequest, NextResponse } from 'next/server';
import { initializeDatabase, getSession, updateSession } from '@/lib/database';
import { withCors } from '@/lib/cors';

// 初始化数据库
let dbInitialized = false;
async function ensureDatabaseInitialized() {
  if (!dbInitialized) {
    await initializeDatabase();
    dbInitialized = true;
  }
}

// GET /api/sessions/[sessionId] - 获取特定会话
async function handleGET(
  request: NextRequest,
  { params }: { params: { sessionId: string } }
) {
  try {
    await ensureDatabaseInitialized();

    const session = await getSession(params.sessionId);
    
    if (!session) {
      return NextResponse.json(
        { error: '会话不存在' },
        { status: 404 }
      );
    }

    return NextResponse.json({ session });
  } catch (error) {
    console.error('获取会话失败:', error);
    return NextResponse.json(
      { error: '获取会话失败' },
      { status: 500 }
    );
  }
}

// PUT /api/sessions/[sessionId] - 更新会话
async function handlePUT(
  request: NextRequest,
  { params }: { params: { sessionId: string } }
) {
  try {
    await ensureDatabaseInitialized();

    const body = await request.json();
    const { endTime, messageCount, status } = body;

    const updates: any = {};
    if (endTime !== undefined) updates.endTime = endTime;
    if (messageCount !== undefined) updates.messageCount = messageCount;
    if (status !== undefined) updates.status = status;

    await updateSession(params.sessionId, updates);

    const updatedSession = await getSession(params.sessionId);
    return NextResponse.json({ session: updatedSession });
  } catch (error) {
    console.error('更新会话失败:', error);
    return NextResponse.json(
      { error: '更新会话失败' },
      { status: 500 }
    );
  }
}

// 导出带 CORS 支持的处理器
export const GET = withCors(handleGET);
export const PUT = withCors(handlePUT);
